using System;
using System.Collections.Generic;
using System.Text;
using Xyne.Events;
using System.Threading;
using Microsoft.Xna.Framework;

namespace Xyne.Utilities
{
    public class EventManager : GameComponent
    {
        // Event callback delegate
        public delegate void EventReceivedDelegate(Event e);
        // Instance
        private static EventManager instance;
        // List of callbacks
        private List<EventReceivedDelegate> callbacks = new List<EventReceivedDelegate>();
        // Queue of to be handled events
        private Queue<Event> events = new Queue<Event>();
        // Queue lock
        private Object queueLock = new Object();

        public static EventManager Instance
        {
            get { return instance; }
            set { instance = value; }
        }

        public List<EventReceivedDelegate> Callbacks
        {
            get { return callbacks; }
        }

        public EventManager(Game game) : base(game)
        {
        }

        public void SendEvent(Event e)
        {
            lock (queueLock)
            {
                events.Enqueue(e);
            }
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            lock (queueLock)
            {
                while (events.Count > 0)
                {
                    Event e = events.Dequeue();
                    for (int i = 0; i < callbacks.Count; i++)
                    {
                        if (callbacks[i] != null)
                        {
                            callbacks[i](e);
                        }
                    }
                }
            }
        }
    }
}
